﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.IO;

namespace PicShare.Server.Helpers
{
    public static class ImageHelpler
    {
        
        public static Bitmap ResizeBitmap(Image srcbmp, int width, int height)
        {
            var newimage = new Bitmap(width, height);
            using (var g = Graphics.FromImage(newimage))
            {
                g.DrawImage(srcbmp, 0, 0, width, height);
            }
            return newimage;
        }

        public static string CreateStringFromImage(Image image)
        {
            if (image != null)
            {
                byte[] array = null;
                using (var ms = new MemoryStream())
                {
                    image.Save(ms, image.RawFormat);
                    array = ms.ToArray();
                }

                return Convert.ToBase64String(array);
            }
            else
            {
                return null;
            }
        }

        public static Image CreateImageFromByteArray(byte[] imageData)
        {
            if (imageData != null)
            {
                Image image;
                using (var inStream = new MemoryStream())
                {
                    inStream.Write(imageData, 0, imageData.Length);

                    image = Image.FromStream(inStream);
                }
                return image;
            }
            else
            {
                return null;
            }

        }

        public static byte[] CreateByteArrayFromImage(Image x)
        {
            var imageConverter = new ImageConverter();
            var xByte = (byte[])imageConverter.ConvertTo(x, typeof(byte[]));
            return xByte;
        }
    }
}